<template>
  <div>
    <el-card style="margin: 30px 0">
      <CategorySelect @changeCategoryId="changeCategoryId" :show="!isShowTable"></CategorySelect>
    </el-card>

    <el-card>
      <div v-show="isShowTable">
        <el-button @click="addAttrFn" type="primary" icon="el-icon-plus" style="margin-bottom: 20px" :disabled="!category3Id">添加属性</el-button>
        <el-table :data="attrList" border>
          <el-table-column type="index" align="center" label="序号" width="80"></el-table-column>
          <el-table-column prop="attrName" label="属性名称" width="150"></el-table-column>
          <el-table-column prop="attrValueList" label="属性值列表">
            <template v-slot="{row}">
              <el-tag v-for="item in row.attrValueList" :key="item.attrId" style="margin:0 20px">{{item.valueName}}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="prop" label="操作" width="150">
            <template v-slot="{row}">
              <el-button type="warning" size="mini" icon="el-icon-edit" @click="editAttr(row)"></el-button>
              <el-button type="danger" size="mini" icon="el-icon-delete"></el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div v-show="!isShowTable">
        <el-form :inline="true" ref="form" label-width="80px">
          <el-form-item label="属性名">
            <el-input v-model="attrInfo.attrName" placeholder="请输入属性名"></el-input>
          </el-form-item>
        </el-form>
        <el-button type="primary" icon="el-icon-plus" :disabled="!attrInfo.attrName" @click="addAttrInfoFn">添加属性值</el-button>
        <el-button @click="isShowTable = true">取消</el-button>
        <el-table :data="attrInfo.attrValueList" style="width: 100%; margin: 20px 0" border>
          <el-table-column align="center" type="index" label="序号" width="80"></el-table-column>
          <el-table-column width="width" prop="prop" label="属性值名称">
            <template v-slot="{row, $index}">
              <el-input
                v-model="row.valueName"
                v-if="row.flag"
                placeholder="请输入属性值名称"
                size="mini"
                @blur="toLook(row)"
                @keyup.native.enter="toLook(row)"
                :ref="$index"
              ></el-input>
              <span style="display:block; height: 30px; width: 80px; line-height: 30px" v-else @click="toEdit(row, $index)">{{row.valueName}}</span>
            </template>
          </el-table-column>
          <el-table-column label="属性值操作">
            <template v-slot="{row, $index}">
              <el-popconfirm :title="`确定删除${row.valueName}吗？`" @onConfirm="delAttrItem($index)">
                <el-button slot="reference" type="danger" icon="el-icon-delete" size="mini"></el-button>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <el-button type="primary" @click="saveChangeFn" :disabled="attrInfo.attrValueList.length < 1">保存</el-button>
        <el-button @click="isShowTable = true">取消</el-button>
      </div>
    </el-card>
  </div>
</template>

<script>
// 按需引入lodash深拷贝
import cloneDeep from "lodash/cloneDeep";
export default {
  data () {
    return {
      category1Id: '',
      category2Id: '',
      category3Id: '',
      attrList: [], // 接收平台属性的数据
      isShowTable: true, // 控制表格的显示与隐藏
      attrInfo: {
        attrName: '', // 属性名
        attrValueList: [
          // 属性值，多个属性值有各自的id和名称
        ],
        categoryId: 0,
        categoryLevel: 3
      },
      flag: true // 切换表单和span标签显示的布尔值
    }
  },
  methods: {
    changeCategoryId(data) {
      if (data.level === 1) {
        this.category2Id = ''
        this.category3Id = ''
        this.category1Id = data.categoryId
      } else if (data.level === 2) {
        this.category3Id = ''
        this.category2Id = data.categoryId
      } else {
        this.category3Id = data.categoryId
        this.getAttrFn()
      }
    },
    // 发请求获取平台数据
    async getAttrFn() {
      let res = await this.$API.attr.getAttrList(this.category1Id, this.category2Id, this.category3Id)
      console.log(res);
      if (res.code === 200) {
        this.attrList = res.data
      }
    },
    // 新增平台数据
    addAttrInfoFn() {
      // 这里新增和修改是共用的，如果是修改操作，则直接把元素的id给过去。如果是新增，则没有id，给过去的是undefined
      this.attrInfo.attrValueList.push({
        attrId: this.attrInfo.id,
        valueName: '',
        flag: true
      })
      this.$nextTick(() => {
        this.$refs[this.attrInfo.attrValueList.length-1].focus()
      })
    },
    // 添加属性按钮被点击
    addAttrFn() {
      this.isShowTable = false
      this.attrInfo = {
        attrName: '',
        attrValueList: [],
        categoryId: this.category3Id,
        categoryLevel: 3
      }
    },
    // 修改按钮被点击
    editAttr(row) {
      this.isShowTable = false
      // console.log(row);把属性赋值过去
      this.attrInfo = cloneDeep(row)
      this.attrInfo.attrValueList.forEach(item => {
        this.$set(item, 'flag', false)
      });
    },
    // 切换查看和编辑
    toLook(row) {
      if(!row.valueName.trim()) return
      let bool = this.attrInfo.attrValueList.some(item => {
        if (row !== item) {
          return row.valueName == item.valueName
        }
      })
      if (bool) return
      row.flag = false
    },
    toEdit(row, index) {
      row.flag = true
      console.log(row,index);
      this.$nextTick(() => {
        this.$refs[index].focus()
      })
    },
    // 删除数据
    delAttrItem(index) {
      // console.log(index)
      this.attrInfo.attrValueList.splice(index, 1)
    },
    // 保存属性的修改
    async saveChangeFn() {
      // 1.如果用户添加了很多空属性值，不应该提交
      // 2.不应该出现flag字段
      this.attrInfo.attrValueList = this.attrInfo.attrValueList.filter(item => {
        if (item.valueName !== '') {
          delete item.flag
          return true
        }
      })
      try {
        await this.$API.attr.addAttrList(this.attrInfo)
        this.getAttrFn()
        this.isShowTable = true
        this.$message.success({type: 'success', message: '保存成功'})
      } catch (error) {
        console.log(error);
      }
    }
  }
}
</script>

<style>

</style>